package tasks.zhuanyeji.TLV问题;

import java.util.ArrayList;
import java.util.List;

public class TLVSolution {
    public static List<String> parseTLV(String hexStream) {
        List<String> result = new ArrayList<>();
        parseRecursive(hexStream, 0, 0, result);
        return result;
    }

    private static void
    parseRecursive(String hexStream, int pos, int level, List<String> result) {
        while (pos < hexStream.length()) {
            if (pos + 4 > hexStream.length()) {
                break;
            }
            String tagHer = hexStream.substring(pos, pos + 4);
            int tagValue = Integer.parseInt(tagHer, 16);
            pos += 4;

            if (pos + 8 > hexStream.length()) {
                break;
            }
            String lenHex = hexStream.substring(pos, pos + 8);
            int len = Integer.parseInt(lenHex, 16);
            pos += 8;

            if (pos + len * 2 > hexStream.length()) {
                break;
            }
            String valueHex = hexStream.substring(pos, pos + 2 * len);
            pos += 2 * len;
            if ((tagValue & 0x8000) != 0) {
                parseRecursive(valueHex, pos, level + 1, result);
            } else {
                result.add(hexToAscii(valueHex));
            }
        }
    }

    private static String hexToAscii(String valueHex) {
        if (valueHex == null || valueHex.isEmpty()) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < valueHex.length(); i = i + 2) {
            String substring = valueHex.substring(i, i + 2);
            int contentValue = Integer.parseInt(substring, 16);
            stringBuilder.append((char) contentValue);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String input = "00000000000a68656c6c6f20776f7264";
        List<String> output = parseTLV(input);
        System.out.println(output); // [0:hello word]
    }
}
